<?php
/**[函数]
 * @Author: happy
 * @Email:  976123967@qq.com
 * @Date:   2015-03-16 22:05:42
 * @Last Modified by:   chen
 * @Last Modified time: 2015-05-31 09:29:14
 */
use Third\PHPMailer;
use Third\Exception;
use Third\SMTP;

/**
 * 用户定义常量
 * @param bool $view 是否显示
 * @param bool $tplConst 是否只获取__WEB__这样的常量
 * @return array
 */

function print_const($view = true, $tplConst = false) {
    $define = get_defined_constants(true);
    $const = $define['user'];
    if ($tplConst) {
        $const = array();
        foreach ($define['user'] as $k => $d) {
            if (preg_match('/^__/', $k)) {
                $const[$k] = $d;
            }
        }
    }
    if ($view) {
        p($const);
    } else {
        return $const;
    }
}



/**
 * 打印输出数据|show的别名
 * @param void $var
 */
function p($var) {
    show($var);
}



/**
 * 打印输出数据
 * @param void $var
 */
function show($var) {
    if (is_bool($var)) {
        var_dump($var);
    } else if (is_null($var)) {
        var_dump(NULL);
    } else {
        echo "<pre style='padding:10px;border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;line-height:18px;'>" . print_r($var, true) . "</pre>";
    }
}

/**
 * 截取长度
 * 使用自定义标签时截取字符串
 * @param $string 字符串
 * @param int $len 长度
 * @param string $end 结尾符
 * @return string
 */
function cms_substr($string, $len = 20, $end = '...')
{
    if(mb_strlen($string,'utf-8')<$len)
        return $string;
    else
        return mb_substr($string, 0, $len, 'utf-8') . $end;
}


/**
 * 获得随机字符串
 * @param int $len 长度
 * @return string
 */
function rand_str($len = 6) 
{
    $data = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $str = '';
    while (strlen($str) < $len)
        $str .= substr($data, mt_rand(0, strlen($data) - 1), 1);
    return $str;
}

/**
 * [keditor 编辑器]
 * @param  [type] $param [description]
 * @return [type]        [description]
 */
function keditor($param)
{
    $name = $param['name'];
    $content = $param['content'];
    $style = isset($param['style'])?$param['style']:1;
    $str='';
    if (!defined("DJ_KEDITOR")) 
    {
        $str .="<script type='text/javascript' src='".__ROOT__."/Core/Org/Keditor/kindeditor-all-min.js'></script>
        ";
        define("DJ_KEDITOR", true);
    }
    $uploadScript=U('keditor_upload',array('SSID'=>session_id()));

    $toolbar = '';
    if($style==2)
    {

        $toolbar = '
            items :["source","code","fullscreen","|","forecolor", "bold", "italic", "underline",
        "removeformat", "|", "justifyleft", "justifycenter", "justifyright", "insertorderedlist",
        "insertunorderedlist", "|", "emoticons", "link"],'; 
        
    }   
            
    $root=__ROOT__;
    $str .=<<<php
        <script type="text/javascript">
        var optionVar ='{$name}';
        KindEditor.ready(function(K) {
                var optionVar= "editor"+optionVar;
                optionVar = K.create('#{$name}', {
                    //cssPath : '../plugins/code/prettify.css',
                    //uploadJson : '$root/Core/Org/Keditor/php/upload_json.php',
                    uploadJson : '{$uploadScript}',
                    fileManagerJson : '$root/Core/Org/Keditor/php/file_manager_json.php',
                    {$toolbar}
                    width:'99%',
                    height:'300px',
                    allowFileManager : true,
                    afterCreate : function() {
                        var self = this;
                        K.ctrl(document, 13, function() {
                            self.sync();
                            K('form[name=example]')[0].submit();
                        });
                        K.ctrl(self.edit.doc, 13, function() {
                            self.sync();
                            K('form[name=example]')[0].submit();
                        });
                    },
                    //langType:'en',
                    afterBlur: function(){this.sync();}
            });
        });
        </script>
        <textarea name="{$name}" id="{$name}" >{$content}</textarea>
php;
    return $str;

}
/**
 * 根据大小返回标准单位 KB  MB GB等
 */
function get_size($size, $decimals = 2)
{
    switch (true) {
        case $size >= pow(1024, 3):
            return round($size / pow(1024, 3), $decimals) . " GB";
        case $size >= pow(1024, 2):
            return round($size / pow(1024, 2), $decimals) . " MB";
        case $size >= pow(1024, 1):
            return round($size / pow(1024, 1), $decimals) . " KB";
        default:
            return $size . 'B';
    }
}

function set_verifystate($state)
{
    switch ($state) {
        case 1:
           return '审核中';
        case 2:
            return '审核通过';
         case 3:
            return '审核失败';
    }
}

function is_pic($src)
{
   return pathinfo($src);
}

/**
 * [postmail 使用phpmailer发送邮件]
 * @param  [type] $to       [收件箱]
 * @param  string $subject  [邮件主题]
 * @param  string $body     [邮件内容]
 * @param  [type] $consignee[收件人描述]
 * @return [type]           [description]
 */
function postmail($to,$subject = '',$body = '',$consignee='')
{
    // 导入类

    # Create object of PHPMailer
    $mail = new PHPMailer();
    $body            = eregi_replace("[\]",'',$body); //对邮件内容进行必要的过滤
    $mail->CharSet ="utf8";//设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
     
    // Inform class to use SMTP
    $mail->IsSMTP();
     
    // Enable this for Testing
    $mail->SMTPDebug  = 0;
     
    // Enable SMTP Authentication
    $mail->SMTPAuth   = true;
     
    // Host of the SMTP Server
    $mail->Host = "smtp.qq.com";            //smtp地址 更改
     
    // Port of the SMTP Server
    $mail->Port = 25;
     
    // SMTP User Name
    $mail->Username   = "邮箱账号更改";   //邮箱账号更改
     
    // SMTP User Password
    $mail->Password = "邮箱密码更改"; //邮箱密码更改
     
    // Set From Email Address
    $mail->SetFrom("邮箱账号更改", C('cfg_name')); //邮箱账号和发件人描述更改
     
    // Add Subject
    $mail->Subject    = $subject;
     
    // Add the body for mail
    $mail->MsgHTML($body);
     
    // Add To Address
    //$consignee ='收件人描述';
    $mail->AddAddress($to, $consignee); //收件人描述更改
     
     
    // Finally Send the Mail
    if(!$mail->Send())
    {
        return array('status'=>false,error=>"Mailer Error: " . $mail->ErrorInfo);
    }
    else
    {
     return array('status'=>true);
    }
}

function set_url($key,$attr,$suffix='')
{
    $s = I('get.s');
    $sArr = explode('-', $s); 

    // 当前高亮
    $cur = '';
    if($sArr[$key] == $attr['attr_value_attr_value_id'])
        $cur = 'class="on"';

    // 更改属性值
    $sArr[$key]=$attr['attr_value_attr_value_id'];  

    // url
    $url = __ACTION__.'/s/'.implode('-', $sArr);

    // 组合a链接
    echo "<a href='{$url}' {$cur}>
         {$attr['attr_value'.$suffix]}
        </a>";
 
}
